<?php

/**
 * This is the model class for table "{{file}}".
 *
 * The followings are the available columns in table '{{file}}':
 * @property integer $file_id
 * @property string $file_pid
 * @property integer $file_fid
 * @property integer $file_status
 * @property integer $file_hits
 * @property integer $file_islocal
 * @property integer $file_isfolder
 * @property integer $file_iscomment
 * @property string $file_name
 * @property string $file_tag
 * @property integer $file_type
 * @property integer $file_owner
 * @property integer $file_created
 * @property integer $file_size
 * @property string $file_ext
 * @property string $file_mine
 * @property string $file_links
 * @property string $file_remark
 */
class File extends CActiveRecord
{
	//local file or not
	const FILE_ISLOCAL = 1;
	const FILE_ISREMOTE = 0;
	
	
	
	//file allow comment or not
	const FILE_COMMENT_ALLOW = 1;
	const FILE_COMMENT_CANCEL = 0;
	
	//file status	
	const FILE_STATUS_RECYCLING = 0;	//放入回收站
	const FILE_STATUS_DRAFT = 1;	//草稿
	const FILE_STATUS_PUBLISHED = 2;	//发布
	const FILE_STATUS_ACHIVE = 3;	//文件存档
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return File the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{file}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('', 'required'),
			array('file_fid, file_status, file_hits, file_islocal, file_isfolder, file_type, file_owner, file_created, file_size', 'numerical', 'integerOnly'=>true),
			array('file_pid, file_mine', 'length', 'max'=>200),
			array('file_name, file_tag, file_ext, file_links', 'length', 'max'=>500),
			array('file_remark', 'safe'),
			array('file_links','file','types'=>'jpg,png,gif','maxSize'=>10*1024*1024,'tooLarge'=>'文件不能超过10M','allowEmpty'=>true),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('file_id, file_pid, file_fid, file_status, file_hits, file_islocal, file_isfolder, file_name, file_tag, file_type, file_owner, file_created, file_size, file_ext, file_mine, file_links, file_remark', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
// 			'product'	=>  array(self::BELONGS_TO, 'Product', 'file_pid'),
			'media' => array(self::BELONGS_TO, 'Media', 'file_id'),
			'owner'		=>  array(self::BELONGS_TO, 'User', 'file_owner')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'file_id' => 'File',
			'file_pid' => 'File Pid',
			'file_fid' => 'File Fid',
			'file_status' => 'File Status',
			'file_hits' => 'File Hits',
			'file_islocal' => 'File Islocal',
			'file_isfolder' => 'File Isfolder',
			'file_name' => 'File Name',
			'file_tag' => 'File Tag',
			'file_type' => 'File Type',
			'file_owner' => 'File Owner',
			'file_created' => 'File Created',
			'file_size' => 'File Size',
			'file_ext' => 'File Ext',
			'file_mine' => 'File Mine',
			'file_links' => 'File Links',
			'file_remark' => 'File Remark',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('file_id',$this->file_id);
		$criteria->compare('file_pid',$this->file_pid,true);
		$criteria->compare('file_fid',$this->file_fid);
		$criteria->compare('file_status',$this->file_status);
		$criteria->compare('file_hits',$this->file_hits);
		$criteria->compare('file_islocal',$this->file_islocal);
		$criteria->compare('file_isfolder',$this->file_isfolder);
		$criteria->compare('file_name',$this->file_name,true);
		$criteria->compare('file_tag',$this->file_tag,true);
		$criteria->compare('file_type',$this->file_type);
		$criteria->compare('file_owner',$this->file_owner);
		$criteria->compare('file_created',$this->file_created);
		$criteria->compare('file_size',$this->file_size);
		$criteria->compare('file_ext',$this->file_ext,true);
		$criteria->compare('file_mine',$this->file_mine,true);
		$criteria->compare('file_links',$this->file_links,true);
		$criteria->compare('file_remark',$this->file_remark,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	
	public function getFileStatus($status)
	{
		switch ($status){
			case self::FILE_STATUS_ACHIVE:
				return Yii::t('common','ACHIVE');
				break;
			case self::FILE_STATUS_DRAFT:
				return Yii::t('common','DRAFT');
				break;
			case self::FILE_STATUS_PUBLISHED:
				return Yii::t('common','PUBLISHED');
				break;
			case self::FILE_STATUS_RECYCLING:
				return Yii::t('common','TRASH');
				break;
			default:
				return 'NULL';
				break;
		}
	}
	
	public function getFileCommentStatus($status)
	{
		switch ($status){
			case self::FILE_COMMENT_ALLOW:
				return Yii::t('common','ALLOW');
				break;
			case self::FILE_COMMENT_CANCEL:
				return Yii::t('common','CANCEL');
				break;
		}
	}
	
	public function generateFileStatusDropdownListArray()
	{
		return array(
			self::FILE_STATUS_PUBLISHED=>self::getFileStatus(self::FILE_STATUS_PUBLISHED),
			self::FILE_STATUS_ACHIVE=>self::getFileStatus(self::FILE_STATUS_ACHIVE),
			self::FILE_STATUS_DRAFT=>self::getFileStatus(self::FILE_STATUS_DRAFT),
			self::FILE_STATUS_RECYCLING=>self::getFileStatus(self::FILE_STATUS_RECYCLING),
		);
	}
	
	public function getFileIsLocal($type)
	{
		switch ($type){
			case self::FILE_ISLOCAL:
				return "LOCAL";
				break;
			case self::FILE_ISREMOTE:
				return "REMOTE";
				break;
			default:
				return "NULL";
				break;
		}
	}
    /**
     * 
     * 此方法用于生成所需要图片
     * @param unknown_type $src	本地源图片地址
     * @param unknown_type $des	本地目标地址
     * @param unknown_type $width	目标图片宽度
     * @param unknown_type $height	目标图片高度
     * @param unknown_type $border	目标图片
	 * @param unknown_type $isMask	是否加水印
	 * @param unknown_type $masksrc	水印图片地址
	 * @param unknown_type $maskpos	水印位置
	 */
	function getPerfectImage($source,$destination,$width,$height,$border=1,$isMask=false,$masksrc='',$maskpos=4)
	{

		try {
			
			$t = new ThumbHandler();
			$t->setSrcImg($source);
			$t->setImgDisplayQuality(90);
			$t->setCutType(1);//指明为手工裁切
			$t->setDstImg($destination);
			
			$w = $t->getSrcImgWidth();
			$h = $t->getSrcImgHeight();
            
            		
			//宽度缩放比例
			$percent = floatval($width/$w)*100;

     		if($isMask){
     			$t->setMaskImg($masksrc);
     			$t->setMaskPosition($maskpos);
     			$t->setMaskImgPct(30);			
     		}
            
            $t->createImg($percent);
			
		}catch(CException $e){
			echo $e->getTraceAsString();
		}
       
//		
//		$pathinfo = pathinfo($src);
//		$ext = $pathinfo['extension'];
//// 		$tmp = './public/upload/'.md5(time().rand(1, 1000)).'.'.$ext;
//		
//		$t = new ThumbHandler();
//		$t->setSrcImg($src);		
//		$t->setImgDisplayQuality(90);
//		$t->setCutType(1);//指明为手工裁切
//		$t->setDstImg($des);
//		
//		$w = $t->getSrcImgWidth();
//		$h = $t->getSrcImgHeight();
//		
//		//宽度缩放比例
//		$num_w = floatval($width/$w)*100;
//		
//		$num = $num_w;
//// 		//如果以宽缩放为标题，则目标图片高度
//// 		$tar_h = $h*$width/$w;
//		
//// 		//高度缩放比例
//// 		$num_h = ($height/$h)*100;
//// 		//如果以高缩放为标准，则目标图片宽度
//// 		$tar_w = $w*$height/$h;
//		
//// 		if($num_w > $num_h && $tar_h>=$height)
//// 		{
//// 			$num = $num_w;
//// 		}else if($num_w > $num_h && $tar_h < $height){
//// 			$num = $num_h;
//// 		}else if($num_w < $num_h && $tar_w >= $width){
//// 			$num = $num_h;
//// 		}else{
//// 			$num = $num_w;
//// 		}
//		
////		$w = $t->getSrcImgWidth();
////		
////		$num = ceil(($width/$w)*100);
//
//		$t->createImg($num);
////		$num = 250/$ss;
////		590*300
////		550*300	72		
//// 		$t = new ThumbHandler();
//// 		$t->setSrcImg($tmp);
//// 		if($isMask){
//// 			$t->setMaskImg($masksrc);
//// 			$t->setMaskPosition($maskpos);
//// 			$t->setMaskImgPct(30);			
//// 		}	
//
//		
//// 		$t->setCutType(2);//指明为手工裁切
//// 		$t->setSrcCutPosition(0, 0);// 源图起点坐标
//// 		$t->setRectangleCut($width-8, $height-8);// 裁切尺寸
//// 		$t->setImgDisplayQuality(90);
//// 		$t->setDstImg($des);
//// 		$t->setDstImgBorder(4,"#dddddd");
//// 		$t->createImg($width,$height);
//		
//// 		unlink($tmp);
	}
	


	/**
	 * 获取文件地址
	 * @param unknown_type $model
	 * @param unknown_type $isUploadPath
	 * @param unknown_type $isThumb
	 * @param unknown_type $path
	 * @return string
	 */
	public function generateOriginFilePath($model, $isUploadPath=true, $isThumb=true, $path=null)
	{
		//Set product picture path	
		if(is_null($path))	
			$filepath = Yii::app()->params['uploadProductPath'];
		else 
			$filepath = $path;
		
		$destination = '';
		if($isUploadPath){
			$destination .= '.'; 
		}
		
		//The original image
		$destination .=  $filepath.date('Y',$model->file_created).'/'.date('m',$model->file_created).'/'.date('d',$model->file_created).'/'.$model->file_links;
		
		if($isThumb){
			
			if ($model !== NULL){
			 
				$destination .= '_thumb.'.$model->file_ext;		
						
			}else{
				
				$destination = Yii::app()->params->missingFolderThumbPath;
				
			}		


		}else {
			
			if ($model !== NULL){
				$destination .= '.'.$model->file_ext;
			}else{
				$destination = Yii::app()->params->missingFolderPath;
			}
			
			
		}
		
		if(!file_exists($destination))
		{
			UtilFile::createDir(dirname($destination));
		}
		
		return $destination;		
	}
	

	/**
	 * 获取文件地址
	 * @param unknown_type $model
	 * @param unknown_type $isUploadPath
	 * @param unknown_type $isThumb
	 * @param unknown_type $path
	 * @return string
	 */
	public function generateFilePath($model, $isUploadPath=true, $isThumb=true, $path=null, $thumbOption=array('width'=>210,'height'=>2000,'border'=>1,'isMask'=>false,'masksrc'=>'./public/images/logo.png','maskpos'=>4))
	{
	   
       extract($thumbOption);       
       
       
	   if($model && $isThumb && !$isUploadPath)
       {       
            $source = self::generateOriginFilePath($model, true, false, $path);
            $target = self::generateOriginFilePath($model, true, true, $path);
            
            if(file_exists($source))
            {
                 if(!file_exists($target) || time()-filemtime($target) >= 3600)
                {
                    self::getPerfectImage($source, $target,$width, $height,$border,$isMask,$masksrc,$maskpos);
                }               
            }
            else
            {
                //如果原始文件不在了，就直接删除Model
                $model->delete();
                
                return '';
            }
            
            

            
        
       }
            
            
        $destination = self::generateOriginFilePath($model, $isUploadPath,$isThumb, $path);
       
       
       
        return $destination;
        		
	}
	
	public function fileStatisticsByType($type)
	{
		$criteria = new CDbCriteria(array(
			'condition'=>'file_type = :file_type',
			'params'=>array(
				':file_type'=>$type
			)
		));
		
		return self::model()->count($criteria);
	}
	
	//进行文件统计
	public function fileStatistic($path)
	{
//		$start = microtime(true);
		
//		$cache = Yii::app()->fileCache;
//		
////		$unique =  UtilTools::generateUniqueId(__CLASS__.__METHOD__.$path);		
//
//		$unique = 'statistics'.UtilTools::generateUniqueId($path);
//	
////		echo $unique;
//		
//		if($cache->get($unique) === false)
//		{

//			echo 'OK--';
			$ar = UtilTools::getDirectorySize($path);
			
//			$cache->set($unique, $ar, 24*3600,new CDirectoryCacheDependency($path));
//			
//		}
//		
//		$end = microtime(true);
//		
//		echo __CLASS__.__METHOD__.$path.($end - $start);
//		
//		return $cache->get($unique);
		
		
		
	}   
    


}